<?php
/**
* This file is part of Webappkit, a packages system for PHP web apps
* @link http://webappkit.net
* @package dj
* @author J.Ducastel <nospam0@ducastel.name>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

/**
 * Urls routing for Dj framework kit
 */
class DjUrlsTool extends WakTool {
    
    function factory($kit,$cfg=null) {
        return new DjUrlsTool($kit,$cfg);
    }
    
    /**
     * try to found route for url
     * @access public
     * @param string $url url path
     * @return DjRoute
     */
    function searchRoute($url) {
        foreach ($this->cfg as $name => $data) {
            $args=$this->_detectPattern($data['pattern'],$url);
            if (is_array($args)) {
                    $route=new DjRoute;
                    $route->set('name',$name);
                    $route->set('args',$args);
                    $route->loadData($data);
                    return $route;
                }
        }
        return false;
    }
    
    /**
     * @var array : urls config : default urls patterns
     */
    var $cfg=array(
        'home'=>array(
            'pattern'=>'^$'
            ,'view'=>'DjViews')
        ,'some_object'=>array(
            'pattern'=>'^obj/([0-9]+)/?([a-z]+)?/?([a-z]+)? id action param'
            ,'view'=>'object_view')
        ,'toto'=>array(
            'pattern'=>'toto'
            ,'view'=>'toto'));
    
    
    /**
     * tries to detect pattern in url
     * if found, returns an array of cpatured vars
     * @access protected
     * @param string $pattern regex that may be followed by an arg names space-separated list
     * @param string $url
     * @return array|false
     */
    function _detectPattern($pattern,$url) {
        // extracting regex from patterns
        $keys=explode(' ',$pattern);
        $regex=array_shift($keys);
        // trying detection
        if (!ereg($regex,$url,$captures))
            return false;
        // pattern found !
        // removing string from captures
        array_shift($captures);
        $args=$captures;
        foreach ($keys as $key) {
            $args[$key]=array_shift($captures);
        }
        return $args;
    }
    
    /**
     * builds a route instance
     * /
    function _buildRoute($name,$data) {
        $route=new DjRoute($data);
        $route->set('name',$name);
        return $route;
    }/**/
}
?>